<?php

namespace App\Models\Basic;

use App\Helpers\Code;
use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;

class DictionaryMember extends BaseModel
{

    protected $table = 'dictionary_members';
    protected $fillable = [
        'dictionary_id', 'parent_id', 'title', 'code', 'description', 'rank', 'state', 'created_by', 'updated_by', 'data_scope',
    ];
    public $sorters = ['rank'];
    public $params = ['title', 'code', 'dictionary'];

    public function dictionary()
    {
        return $this->belongsTo('App\Models\Basic\Dictionary', 'dictionary_id');
    }

    public function parent()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'parent_id');
    }

    /**
     * 添加字典成员
     * @param $data
     * @return int|null
     */
    public function addDictionaryMember($data)
    {
        if (isset($data['parent_id'])) {
            $parent = $this->where('dictionary_id', $data['dictionary_id'])->find($data['parent_id']);

            if (!$parent) {
                return null;
            }
        }

        $title = $this->where('title', $data['title'])->where('dictionary_id', $data['dictionary_id'])->count();
        if ($title > 0) {
            return Code::INSIDE_ERROR;
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    /**
     * 编辑字典成员
     * @param $data
     * @param $id
     * @return int|null
     */
    public function editDictionaryMember($data, $id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        //判断名称是否重复
        $title = $this->where('title', $data['title'])->where('dictionary_id', $data['dictionary_id'])->where('id', '!=', $id)->count();
        if ($title > 0) {
            return Code::INSIDE_ERROR;
        }

        if (isset($data['parent_id'])) {
            //判断父级是否自身
            if ($data['parent_id'] == $id) {
                return Code::INSIDE_ERROR_1;
            }

            //父级库位是否存在
            $parent = $this->where('dictionary_id', $data['dictionary_id'])->find($data['parent_id']);
            if (!$parent) {
                return Code::INSIDE_ERROR_2;
            }

            //判断父级是否为其子集
            $dictionary = $this->where('dictionary_id', $data['dictionary_id'])->get(['id', 'parent_id'])->toArray();
            if (count($dictionary) > 0) {
                $childrenArr = $this->_getAllChild($dictionary, $id);
                $childrenIds = array_column($childrenArr, 'id');
                if (in_array($data['parent_id'], $childrenIds)) {
                    return Code::INSIDE_ERROR_3;
                }
            }

        }

        $data['updated_by'] = Auth::id();

        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 获取字典成员列表
     * @param $limit
     * @param $sorter
     * @param $search
     * @param $defaultSorter
     * @return mixed
     */
    public function getDictionaryMemberList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if (!isset($defaultSorter)) {
            $model = $this->orderBy('created_at', 'desc');
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->select(['id', 'dictionary_id', 'parent_id', 'title', 'code', 'description', 'rank', 'state', 'created_at'])
            ->with(['dictionary:id,title,code', 'parent:id,title,code']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                case 'title':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
                case 'dictionary':
                    $model->whereHas('dictionary', function ($dictionary) use ($value) {
                        $dictionary->where('title', $value);
                    });
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }

    //获取字典成员子集
    public function _getAllChild($data, $id)
    {
        $arr = [];
        foreach ($data as $v) {
            if ($v['parent_id'] == $id) {
                $child['id'] = $v['id'];
                $arr[] = $child;
                $arr = array_merge($arr, $this->_getAllChild($data, $v['id']));
            }
        }
        return $arr;
    }
}
